<?php
/**
 * 初始化缓存，使用都需要调用此步骤
 */
function initCache()
{
    /*S(array(
        'type' => 'Redis',
        'host' => '127.0.0.1',
        'port' => '6379',
        'prefix' => 'think',
        'expire' => 3600)
    );*/
}

/*
 * 省级联动
 */
function getRegionList($parentId){
    if(isset($parentId)){
        $list = array("" => "");
        $regionLists = M("region")->where("parent_id='$parentId'")->cache(true)->select();
        for ($j = 0; $j < count($regionLists); $j++) {
            $region = $regionLists[$j];
            $key = $region['id'];
            $list[$key] = $region['name'];
        }

        return $list;
    }else{
        return null;
    }
}

/**
 * 获取配置
 */
function getConfig($module, $code = '')
{
    $system = S('system');

    // 如果缓存没有数据
    if (empty($system)) {
        $system = loadSystem();
    }

    if (empty($system)) {
        return null;
    }

    // 如果没有code
    if (empty($code)) {
        return $system[$module];
    } else {
        if (empty($system[$module])) {
            return null;
        } else {
            return $system[$module][$code];
        }
    }
}

/**
 * 加载系统配置
 */
function loadSystem()
{
    S('system', null);
    $system = selSystem();
    S('system', $system, 0);
    return $system;
}

/**
 * 检索系统表
 */
function selSystem()
{
    $modules = M('system')->field("module")->group("module")->select();
    $moduleList = array();
    for ($i = 0; $i < count($modules); $i++) {
        $module = $modules[$i]['module'];
        $configs = array();
        $subModules = M('system')->where(array('module' => $module))->select();
        for ($j = 0; $j < count($subModules); $j++) {
            $subModule = $subModules[$j];
            $key = $subModule['code'];
            $configs[$key] = $subModule['val'];
        }
        $moduleList[$module] = $configs;
    }
    return $moduleList;
}

/**
 * 获取下拉框，或者值
 * 没有模板名称返回所有，有模板返回对应下拉框，有code返回对应名称
 *
 * @param string $module 模板名称
 * @param string $code code
 * @param bool $hasEmpty 是否包含空值
 * @return array|mixed|null
 */
function getDropdownList($module = '', $code = '' , $hasEmpty = true)
{
    $dropdown = S('dropdown');

    // 如果缓存没有数据
    if (empty($dropdown)) {
        $dropdown = loadDropdown();
    }

    if (empty($dropdown)) {
        return null;
    }

    if (empty($module)) {
        return $dropdown;
    }

    // 如果没有code
    if (empty($code)) {

        // 是否包含空值
        if($hasEmpty){

            $dropdownList  = array("" => "");
            $dropdownList = $dropdownList + $dropdown[$module];
            return $dropdownList;
        }else{
            return $dropdown[$module];
        }
    } else {
        if (empty($dropdown[$module])) {
            return null;
        } else {
            return $dropdown[$module][$code];
        }
    }
}

/**
 * 加载下拉框
 */
function loadDropdown()
{
    S('dropdown', null);
    $dropdown = selDropdown();
    S('dropdown', $dropdown, 0);
    return $dropdown;
}

/**
 * 检索下拉框
 * @return array
 */
function selDropdown()
{
    $modules = M('dropdown')->field("module")->group("module")->select();
    $moduleList = array();
    for ($i = 0; $i < count($modules); $i++) {
        $module = $modules[$i]['module'];
        $configs = array();
        $subModules = M('dropdown')->where(array('module' => $module))->order("sort asc")->select();
        for ($j = 0; $j < count($subModules); $j++) {
            $subModule = $subModules[$j];
            $key = $subModule['code'];
            $configs[$key] = $subModule['val'];
        }
        $moduleList[$module] = $configs;
    }
    return $moduleList;
}

/**
 * 加载首页商品
 */
function loadIndexProduct(){
    S('indexProducts', null);
    $products = M('product')->field("id,name,price,img")->where(array("isUp" => '1', "isDelete" => '2'))->order(" id desc")->limit(6)->select();
    S('indexProducts', $products, 0);
    return $products;
}

/**
 * 获取首页商品列表
 *
 * @return mixed
 */
function getIndexProduct()
{
    $products = S('indexProducts');
    if (empty($products)) {
        $products = loadIndexProduct();
    }
    return $products;
}

/**
 * 加载首页公司信息
 */
function loadIndexCompany(){
    S('indexCompany', null);
    $company = M('company')->field("id,name,content,img,address")->find();
    S('indexCompany', $company, 0);
    return $company;
}

// 获取公司简介
function getIndexCompany(){
    $company = S('indexCompany');
    if (empty($company)) {
        $company = loadIndexCompany();
    }
    return $company;
}

/**
 * 加载轮播图
 */
function loadIndexShow(){
    S('indexShow', null);
    $show = M('show')->field("title,url,img")->order("sort asc")->limit(2)->select();
    S('indexShow', $show, 0);
    return $show;
}

// 获取轮播图
function getIndexShow(){
    $show = S('indexShow');
    if (empty($show)) {
        $show = loadIndexShow();
    }
    return $show;
}

/**
 * 加载会员公告
 */
function loadMemberNotice(){
    S('IndexNotice', null);
    $Notice = M('article')->order(" updateTime desc")->where(array("type" => 1))->select();
    S('IndexNotice', $Notice, 0);
    return $Notice;
}

/**
 * 获取会员公告
 * @return mixed 公告列表
 */
function getMemberNotice(){
    $show = S('IndexNotice');
    if (empty($show)) {
        $show = loadMemberNotice();
    }
    return $show;
}

/**
 * 加载会员常见问题
 * @return mixed 常见问题列表
 */
function loadMemberQuestion(){
    S('IndexQuestion', null);
    $Question = M('article')->order(" updateTime desc")->where(array('catalog' => 2, "articleType" => 2))->select();
    S('IndexQuestion', $Question , 0);
    return $Question;
}

/**
 * 获取全部商城分类
 */
function loadAllCates() {
    S('AllCates', null);
    $cates = M('category')->order("sortOrder asc")->select();
    S('AllCates', $cates , 0);
    return $cates;
}

/**
 * 获取会员常见问题
 * @return mixed 常见问题列表
 */
function getMemberQuestion(){
    $show = S('IndexQuestion');
    if (empty($show)) {
        $show = loadMemberQuestion();
    }
    return $show;
}

/**
 * 获取商城分类
 */
function getAllCates(){
    $cates = S('AllCates');
    if (empty($show)) {
        $cates = loadAllCates();
    }
    return $cates;
}

/**
 * 获取会员公告
 * @return mixed 公告列表
 */
function getAgenNotice(){
    $show = S('AgenNotice');
    if (empty($show)) {
        $show = loadAgenNotice();
    }
    return $show;
}

/**
 * 加载会员公告
 */
function loadAgenNotice(){
    S('AgenNotice', null);
    $Notice = M('article')->order(" updateTime desc")->where(array('catalog' => 1, "articleType" => 1))->select();
    S('AgenNotice', $Notice, 0);
    return $Notice;
}

/**
 * 清空系统缓存，兼容sae
 */
function sp_clear_cache()
{
    import("ORG.Util.Dir");
    $dirs = array();
    $rootdirs = sp_scan_dir(RUNTIME_PATH . "*");
    $noneed_clear = array(".", "..");
    $rootdirs = array_diff($rootdirs, $noneed_clear);
    foreach ($rootdirs as $dir) {

        if ($dir != "." && $dir != "..") {
            $dir = RUNTIME_PATH . $dir;
            if (is_dir($dir)) {
                $tmprootdirs = sp_scan_dir($dir . "/*");
                foreach ($tmprootdirs as $tdir) {
                    if ($tdir != "." && $tdir != "..") {
                        $tdir = $dir . '/' . $tdir;
                        if (is_dir($tdir)) {
                            array_push($dirs, $tdir);
                        } else {
                            @unlink($tdir);
                        }
                    }
                }
            } else {
                @unlink($dir);
            }
        }
    }
    $dirtool = new \Dir("");
    foreach ($dirs as $dir) {
        $dirtool->delDir($dir);
    }

    if (sp_is_sae()) {
        $global_mc = @memcache_init();
        if ($global_mc) {
            $global_mc->flush();
        }

        $no_need_delete = array("THINKCMF_DYNAMIC_CONFIG");
        $kv = new SaeKV();
        // 初始化KVClient对象
        $ret = $kv->init();
        // 循环获取所有key-values
        $ret = $kv->pkrget('', 100);
        while (true) {
            foreach ($ret as $key => $value) {
                if (!in_array($key, $no_need_delete)) {
                    $kv->delete($key);
                }
            }
            end($ret);
            $start_key = key($ret);
            $i = count($ret);
            if ($i < 100) break;
            $ret = $kv->pkrget('', 100, $start_key);
        }

    }
}

/**
 * 判断是否为SAE
 */
function sp_is_sae()
{
    if (defined('APP_MODE') && APP_MODE == 'sae') {
        return true;
    } else {
        return false;
    }
}

/**
 * 检索系统表
 */
function loadLevel()
{
    S('level', null);
    $list = array("" => "");
    $agenLevels = M('agenLevel')->field("level,name")->select();
    for ($j = 0; $j < count($agenLevels); $j++) {
        $agenLevel = $agenLevels[$j];
        $key = $agenLevel['level'];
        $list[$key] = $agenLevel['name'];
    }

    S('level', $list, 0);
    return $list;
}

/**
 * 返回等级下拉框
 *
 * @param string $level 如果有等级返回名称
 * @return array|mixed 如果有等级返回名称
 */
function getLevelList($level = ''){
    $list = S("level");

    if(empty($list)){
        $list = loadLevel();
    }

    if(!empty($level)){
        return $list[$level];
    }else{
        return $list;
    }
}

/**
 * 获取物流公司信息
 */
function getLogisticsList(){
    $list = array("" => "");
    $logistics = M('logistics')->field("code,name")->select();
    for ($j = 0; $j < count($logistics); $j++) {
        $lgtics = $logistics[$j];
        $key = $lgtics['code'];
        $list[$key] = $lgtics['name'];
    }
    return $list;
}